package com.ygnn.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ygnn.reggie.common.BaseContext;
import com.ygnn.reggie.common.R;
import com.ygnn.reggie.entity.Orders;
import com.ygnn.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }
    @GetMapping("/userPage")
    public R<Page> userPage(@RequestParam("page") Integer currentPage,Integer pageSize){
        Page<Orders> page=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Orders> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getCheckoutTime);
        orderService.page(page,wrapper);
        if(pageSize>0) return R.success(page);
        else return R.error("没有数据");
    }
    @GetMapping("/page")
    public R<Page> page(@RequestParam("page") Integer currentPage,Integer pageSize) {
        Page<Orders> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getCheckoutTime);
        orderService.page(page, wrapper);
        page.setRecords(page.getRecords().stream().map(item -> {
            if (item.getUserName() == null) item.setUserName("没有设置用户名");
            return item;
        }).collect(Collectors.toList()));
        if (pageSize > 0) return R.success(page);
        else return R.error("没有数据");
    }
    @PutMapping
    public R<String> paisong(@RequestBody Orders orders)
    {
        orders.setStatus(3);
        orderService.updateById(orders);

        return R.success("派送成功");
    }

}
